/******************************************************************************
*
* This file is part of FreeTrack (http://code.google.com/p/qtfreetrack).
* BY Willy Gardiol (willy@gardiol.org)
*
* FreeTrack is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FreeTrack is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar.  If not, see <http://www.gnu.org/licenses/>
*
******************************************************************************/

#include "mainselector.h"
#include "configwidget.h"
#include "ftpushbutton.h"
#include "layermanager.h"
#include "fthelpwidget.h"
#include "layertrack.h"
#include "ftlabel.h"
#include "freetrack.h"
#include "filenavigator.h"
#include "freetrackdialog.h"


extern ConfigWidget* conf;
extern FreeTrack* freetrackObject;
extern LayerManager* layerManager;

MainSelector* mainSelector;

MainSelector::MainSelector(QWidget *parent) :
    FreeTrackWidget(parent)
{
    mainSelector = this;

    livetrack = layerManager->getLivetrack();

    // Initialize Live Track buttons and stuff
    live_label = new FTLabel( tr("Manage LiveTrack"));
    live_label->setAlignment( Qt::AlignCenter );
    live_start = new FTPushButton( QIcon(":/icons/record.png"), BUTTON_SIZE);
    live_start->setCheckable(true);
    live_reset = new FTPushButton( QIcon(":/icons/reset.png"), ICON_SIZE_SMALL);
    live_edit = new FTPushButton( QIcon(":/icons/edit.png"), BUTTON_SIZE);
    live_load = new FTPushButton( QIcon(":/icons/load-track.png"), ICON_SIZE);
    live_save = new FTPushButton( QIcon(":/icons/save.png"), ICON_SIZE);
    live_help = new FTHelpWidget(
            tr("<center|b>LiveTrack</center>"\
        "<justify>The LiveTrack is a path that tracks where you are going. "\
        "By recording a LiveTrack you are storing a record of your trip, your "\
        "hike, your sport activity.</justify>"\
        "<justify>You can use these buttons to start/stop recording a LiveTrack, to load or save it, "\
        "to reset or to edit it.</justify>"\
        "<center|b>Load and Save</center>"\
        "<justify>You can save your track by tapping the 'save' button here. This will open up "\
        "a dialog box where you can choose the folder and the filename where you want to store "\
        "the LiveTrack. Think of it like it is a 'save as...' button. You can also reload a "\
        "previusly saved track with the 'load' button. By doing this, you can continue a track "\
        "from where you left it the last time. There is also an autosave feature (which can be "\
        "enabled or disabled via the FreeTrack configuration page) which will take care of saving "\
        "the track for you.</justify>"\
        "<center|b>Start and Stop recording</center>"\
        "<justify>You can start or stop the recording with the 'gear' button. When you start a new "\
        "Live Track, you will be prompted for a filename. If you dont want to save (yet) this track "\
        "you can simply leave it empty and the Live Track will start without a filename. Please note "\
        "that not setting a filename the autosave feature will be disabled.</justify>"\
        "<center|b>Edit or Reset</center>"\
        "<justify>By tapping on the 'edit' button you will open the track edit dialog. From here, you "\
        "can change the Live Track color, size, title and description. You can also delete or modify waypoints "\
        "and, if you have an account, upload it to www.gobreacrumbs.com.</justify>"\
        "<justify>The 'reset' button let you delete all the contents of the Live Track. Be careful, this "\
        "action cannot be undone!</justify>"));

    // Build the "screen rotation" buttons
    labelOrientation = new FTLabel( tr("Set screen orientation") );
    labelOrientation->setAlignment( Qt::AlignCenter );
    helpOrientation = new FTHelpWidget(
            tr("<center|b>Orientate Screen</center>" \
               "<justify>Sometimes you need to force FreeTrack to show in 'vertical' (also called 'portrait') or "\
               "to show in 'horizontal' (also called 'landscape') mode. Otherwise FreeTrack will adapt to the "\
               "screen orientation automatically.</justify>"\
               "<justify>By selecting the first button, the screen will rotate in landscape mode regardless of the "\
               "real screen orientation.</justify>"\
               "<justify>By selecting the second button, the screen will rotate portrait mode regardelss of the "\
               "real screen orientation.</justify>"\
               "<justify>By selecting the third button, the screen will be free to adapt to the phone orientation.</justify>"\
               "<justify>In the 'configuration' page you can select whether you want FreeTrack to remember your selection "\
               "the next time you open it.</justify>"));
    Orientation orient = conf->getOrientation();
    // Portrait button
    portrait = new FTPushButton( QIcon( ":/icons/5800_v.png"), ICON_SIZE_BIG);
    portrait->setCheckable(true);
    if ( orient == vertical )
        portrait->setChecked(true);
    connect(  portrait, SIGNAL(clicked()),
                  this, SLOT(selectPortrait()) );
    // Landscape button
    landscape = new FTPushButton( QIcon( ":/icons/5800_h.png"), ICON_SIZE_BIG);
    landscape->setCheckable(true);
    if ( orient == horizontal )
        landscape->setChecked(true);
    connect( landscape, SIGNAL(clicked()),
                  this, SLOT(selectLandscape()) );
    // Auto rotate button
    automatic = new FTPushButton( QIcon( ":/icons/5800_a.png"), ICON_SIZE_BIG);
    automatic->setCheckable(true);
    if ( orient == automaticOrientation )
        automatic->setChecked(true);
    connect( automatic, SIGNAL(clicked()),
                  this, SLOT(selectAutomatic()) );


    // Tracking table button...
    helpTable = new FTHelpWidget(
            tr("<center|b>The Tracking Table</center>"\
               "<justify>The Tracking Table shows the area around your current position and Live Track: you can move "\
               "around by tapping and moving the finger on the screen, also you can zoom in and out "\
               "by clicking on the two icons with the 'plus' and the 'minus'.</justify>"\
               "<justify>The Tracking Table is also the place where you can see all the maps that you have "\
               "loaded and calibrated, and all the tracks you have loaded trough the Layers page.</justify>"\
               "<justify>You can activate the 'follow' mode by clicking on the 'center' icon: when in 'follow' "\
               "mode the tracking table will automatically center on the last known GPS position. The 'follow' "\
               "mode will be deactivated as soon as you move the tracking table around with the finger.</justify>"\
               "<justify>Also from the Tracking Table you can drop waypoints on the Live Track. Just move until the "\
               "desired position is directly in the middle of the screen and then tap on the waypoint icon! You "\
               "will be prompted with name and description for your new waypoint. Waypoints can be managed from "\
               "the Live Track edit page.</justify>") );
    openTable = new FTPushButton(QIcon( ":/icons/table.png"), ICON_SIZE_LARGE);
    openTable->setText( tr("Tracking table") );
    connect( openTable, SIGNAL(clicked()),
             freetrackObject, SLOT(showTable()) );

    // GPS button...
    helpGps = new FTHelpWidget(
            tr("<center|b>The GPS datak page</center>"\
               "<justify>The GPS data page is where you will find your current GPS "\
               "position and data.</justify>"\
               "<justify>From this page you can see all the GPS data: latitude, longitude, altitude, precision and speed. "\
               "If there is no current GPS fix, all the values will be empty and the GPS status button on the bottom of "\
               "the screen will be red.</justify>") );
    openGps = new FTPushButton( QIcon( ":/icons/gps.png"), ICON_SIZE_BIG);
    openGps->setText( tr("GPS data") );
    connect( openGps, SIGNAL(clicked()),
             freetrackObject, SLOT(showGps()) );


    // Layers button
    helpLayers = new FTHelpWidget(
            tr("<center|b>The layers page</center>"\
               "<justify>From this page you can load maps and tracks.</justify>"\
               "<justify>Any item that you load will be visible on the Tracking Table (maps will be visible only "\
               "after they have been calibrated)</justify>"\
               "<justify>Items will be drawn from bottom to top, so keep your tracks on the top and your maps "\
               "on the bottom, of the maps will cover the tracks and you will not see them!</justify>") );
    openLayers = new FTPushButton( QIcon(":/icons/Layers.png"), ICON_SIZE_BIG);
    openLayers->setText( tr("Tracks / Maps"));
    connect( openLayers, SIGNAL(clicked()),
             freetrackObject, SLOT(showLayers()) );

    // About button...
    openAbout = new FTPushButton( QIcon( ":/icons/about.png"), ICON_SIZE_BIG);
    connect( openAbout, SIGNAL(clicked()),
             freetrackObject, SLOT(showAbout()) );

    // Config button
    openConfig = new FTPushButton( QIcon(":/icons/config.png"), ICON_SIZE_BIG);
    connect( openConfig, SIGNAL(clicked()),
             freetrackObject, SLOT(showConfig()) );

    // exit button:
    openQuit = new FTPushButton( QIcon( ":/icons/exit.png"), ICON_SIZE);
    connect( openQuit, SIGNAL(clicked()),
             freetrackObject, SLOT(askQuit()) );

    // hide button
    openHide = new FTPushButton( QIcon(":/icons/minimize.png"), QSize( 64,48 ) );
    // Connect the hide button
    connect(openHide, SIGNAL(clicked()),
            freetrackObject, SLOT(hideMe()));


    // Connect LiveTrack buttons
    connect( live_start, SIGNAL(clicked(bool)),
                   this, SLOT(startRecording(bool)));
    connect( live_load, SIGNAL(clicked()), this, SLOT(loadLive()));
    connect( live_save, SIGNAL(clicked()), this, SLOT(saveLive()));
    connect( live_reset, SIGNAL(clicked()), this, SLOT(resetLive()));
    connect( live_edit, SIGNAL(clicked()), this, SLOT(editLive()));

}

void MainSelector::selectLandscape()
{
    if ( landscape->isChecked() )
    {
        conf->setOrientation( horizontal );
        portrait->setChecked(false);
        automatic->setChecked(false);
    }
    else
        landscape->setChecked(true);
}

void MainSelector::selectPortrait()
{
    if ( portrait->isChecked() )
    {
        conf->setOrientation( vertical );
        landscape->setChecked(false);
        automatic->setChecked(false);
    }
    else
        portrait->setChecked(true);
}

void MainSelector::selectAutomatic()
{
    if ( automatic->isChecked() )
    {
        conf->setOrientation( automaticOrientation );
        portrait->setChecked(false);
        landscape->setChecked(false);
    }
    else
        automatic->setChecked(true);
}


void MainSelector::changeTracking()
{
    live_start->click();
}

void MainSelector::startRecording(bool rec )
{
    if ( rec )
        if ( !livetrack->isFilenameSet() )
            saveLive();
    livetrack->startTracking(rec);
    emit liveStatusChange(rec);
}

void MainSelector::editLive()
{
    FreeTrackDialog* dialog = new FreeTrackDialog( livetrack->getConfigureLayer() );
    dialog->exec();
    delete dialog;
}

void MainSelector::resetLive()
{

    if ( QMessageBox::question( this,
                                tr("reset LiveTrack"),
                                tr("Really reset?"),
                                QMessageBox::Yes|QMessageBox::No,
                                QMessageBox::NoButton ) != QMessageBox::Yes )
        return;
    // This will take care of the case where the track has not been saved ever (not filename is set)
    if ( livetrack->isModified() )
        saveLive();
    else // This will take care of the case where the track has been quicksaved and must be converted to GPX.
        livetrack->processQuickSave();
    if ( live_start->isChecked() )
        live_start->setChecked(false);
    livetrack->resetTrack();
}


void MainSelector::loadLive()
{
    if ( livetrack->isModified() )
    {
        if ( QMessageBox::question( this,
                                    tr("Load LiveTrack"),
                                    tr("Really load an existing track? Current track will be lost"),
                                    QMessageBox::Yes|QMessageBox::No,
                                    QMessageBox::NoButton ) != QMessageBox::Yes )
            return;
        saveLive();
    }
    QString file = FileNavigator::openTrack( tr("Load live track...") );
    if ( file != "" )
        livetrack->loadTrack(file);
}

void MainSelector::saveLive()
{
    if (QMessageBox::question( this,
                               tr("Save LiveTrack"),
                               tr("Save current LiveTrack?"),
                               QMessageBox::Yes|QMessageBox::No,
                               QMessageBox::NoButton ) != QMessageBox::Yes )
        return;
    livetrack->saveTrack(true);
}

QLayout* MainSelector::createHorizontal()
{
    QVBoxLayout* grid = new QVBoxLayout();

    QHBoxLayout* liveGrid = new QHBoxLayout();
    liveGrid->addWidget( live_help );
    liveGrid->addWidget( live_label );
    liveGrid->addWidget( live_start );
    liveGrid->addWidget( live_save );
    liveGrid->addWidget( live_load );
    liveGrid->addWidget( live_edit );
    liveGrid->addWidget( live_reset );
    grid->addLayout( liveGrid );

    QHBoxLayout* hgrid;
    QHBoxLayout* sGrid = new QHBoxLayout();
    QVBoxLayout* left = new QVBoxLayout();
    QVBoxLayout* right = new QVBoxLayout();
    sGrid->addLayout( left );
    sGrid->addLayout( right );
    grid->addLayout( sGrid );


    hgrid = new QHBoxLayout();
    hgrid->addWidget( openQuit );
    hgrid->addWidget( openHide  );
    right->addLayout( hgrid );

    hgrid = new QHBoxLayout();
    hgrid->addWidget( openAbout );
    hgrid->addWidget( openConfig );
    right->addLayout( hgrid );

    hgrid = new QHBoxLayout();
    hgrid->addWidget( labelOrientation );
    right->addLayout( hgrid );
    hgrid = new QHBoxLayout();
    hgrid->addWidget( landscape );
    hgrid->addWidget( portrait );
    hgrid->addWidget( automatic );
    hgrid->addWidget( helpOrientation );
    right->addLayout( hgrid );

    hgrid = new QHBoxLayout();
    hgrid->addWidget( openTable );
    hgrid->addWidget( helpTable );
    left->addLayout( hgrid );

    hgrid = new QHBoxLayout();
    hgrid->addWidget( openGps );
    hgrid->addWidget( helpGps );
    left->addLayout( hgrid );

    hgrid = new QHBoxLayout();
    hgrid->addWidget( openLayers );
    hgrid->addWidget( helpLayers );
    left->addLayout( hgrid );

    return grid;
}

QLayout* MainSelector::createVertical()
{
    QVBoxLayout* grid = new QVBoxLayout();

    QHBoxLayout* liveGrid = new QHBoxLayout();
    liveGrid->addWidget( live_label );
    liveGrid->addWidget( live_help );
    grid->addLayout( liveGrid );
    liveGrid = new QHBoxLayout();
    liveGrid->addWidget( live_start );
    liveGrid->addWidget( live_save );
    liveGrid->addWidget( live_load );
    liveGrid->addWidget( live_edit );
    liveGrid->addWidget( live_reset );
    grid->addLayout( liveGrid );

    grid->addStretch();

    QHBoxLayout* hgrid = new QHBoxLayout();
    hgrid->addWidget( openTable );
    hgrid->addWidget( helpTable );
    grid->addLayout( hgrid );

    hgrid = new QHBoxLayout();
    hgrid->addWidget( openGps );
    hgrid->addWidget( helpGps );
    grid->addLayout( hgrid );

    hgrid = new QHBoxLayout();
    hgrid->addWidget( openLayers );
    hgrid->addWidget( helpLayers );
    grid->addLayout( hgrid );

    grid->addWidget( labelOrientation );
    hgrid = new QHBoxLayout();
    hgrid->addWidget( landscape );
    hgrid->addWidget( portrait );
    hgrid->addWidget( automatic );
    hgrid->addWidget( helpOrientation );
    grid->addLayout( hgrid );

    grid->addStretch();

    hgrid = new QHBoxLayout();
    hgrid->addWidget( openQuit );
    hgrid->addWidget( openAbout );
    hgrid->addWidget( openConfig );
    hgrid->addWidget( openHide  );
    grid->addLayout( hgrid );


    return grid;
}
